package com.yeskery.transfer.data;

import com.yeskery.transfer.config.DataBaseProperties;
import com.yeskery.transfer.core.SproutException;
import lombok.Setter;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

/**
 * 连接池对象
 *
 * @author shuangjiang.du
 * @date 2018-12-13 21:10
 * @version 1.0
 */
public class SproutDataSource implements DataSource {

	/** 数据库配置对象 */
	private DataBaseProperties.TransferProperties transferProperties;

	/** 数据库连接工具 */
	private ConnectionKit connectionKit;

	/** 最大连接数 */
	@Setter
	private int maxSize = 8;

	/** 连接集合 */
	private List<Connection> connectionList = new LinkedList<>();

	/**
	 * 创建一个数据源对象
	 * @param transferProperties 数据库配置对象
	 * @param connectionKit 数据库连接工具
	 */
	public SproutDataSource(DataBaseProperties.TransferProperties transferProperties, ConnectionKit connectionKit) {
		this.transferProperties = transferProperties;
		this.connectionKit = connectionKit;
		init();
	}

	/**
	 * 创建一个数据源对象
	 * @param transferProperties 据库配置对象
	 * @param connectionKit 数据库连接工具
	 * @param maxSize 最大连接数
	 */
	public SproutDataSource(DataBaseProperties.TransferProperties transferProperties, ConnectionKit connectionKit,
			int maxSize) {
		this.transferProperties = transferProperties;
		this.connectionKit = connectionKit;
		this.maxSize = maxSize;
		init();
	}

	/**
	 * 关闭所有的数据源
	 */
	public void closeAllConnections() {
		//记录最后一次异常，返回给调用方
		SQLException exception = null;
		for (Connection connection : connectionList) {
			try {
				connection.close();
			} catch (SQLException e) {
				exception = e;
			}
		}
		if (exception != null) {
			throw new SproutException("An error occurred while closing the database connection.", exception);
		}
	}

	@Override
	public synchronized Connection getConnection() throws SQLException {
		for (Connection connection : connectionList) {
			if (connection.isValid(1)) {
				return connection;
			}
		}
		if (connectionList.size() < maxSize) {
			try {
				Connection connection = connectionKit.getConnection(transferProperties);
				connectionList.add(connection);
				return connection;
			} catch (ClassNotFoundException e) {
				throw new SproutException("Database driver does not exist.", e);
			}
		}
		return null;
	}

	@Override
	public Connection getConnection(String username, String password) throws SQLException {
		return getConnection();
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		return null;
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		return false;
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		return null;
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {

	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {

	}

	@Override
	public int getLoginTimeout() throws SQLException {
		return 0;
	}

	@Override
	public Logger getParentLogger() throws SQLFeatureNotSupportedException {
		return Logger.getLogger(DataSource.class.getName());
	}

	/**
	 * 初始化连接信息
	 */
	private void init() {
		int defaultSize = 2;
		if (maxSize < defaultSize) {
			maxSize = defaultSize;
		}
		for (int i = 0;i < maxSize / defaultSize;i++) {
			try {
				connectionList.add(connectionKit.getConnection(transferProperties));
			} catch (ClassNotFoundException | SQLException e) {
				throw new SproutException("Database connection creation failed", e);
			}
		}
	}
}
